/* 
 * Course: cs201
 * Name: jiangkai
 * Homework: hw3
 * Date: May 2
 * 
 * First three letters of my odin account:  jia
 * First Stage: 'j' :'i' to 'l':  Swap bytes c0 and c2.
 * Second Stage: 'i' : 'i' to 'l':  Swap bits b7 and b3, Swap bits b6 and b2.
 * Third Stage: 'a' : 'a' to 'd':  XOR bytes c0 and c3 with u3. u3('a')
 */

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char const *argv[]){

	FILE * fp;
	long size;
	char *tmp;
	int i,swap;

	//open the file
	fp = fopen( argv[1], "r+b" );
	
	// obtain file size
	fseek(fp, 0, SEEK_END);
	size = ftell(fp);
	rewind(fp);

	// allocate memory to contain the whole file
	tmp = (char *)malloc(sizeof(char)*size );

	// copy the file into char array
	fread(tmp, 1, size, fp);

	//step 1
	//swap c0 and c2
	for( i = 0; i < size; i += 4 ){
		swap = tmp[i];
		tmp[i] = tmp[i+2];
		tmp[i+2] = swap; 
	}

	//step 2
	//swap bit b7 with b3   swap bit b6 with b2
	// x & (1100 0000)b >> 4 (shift 4 bits right) 
	// x & (0000 1100)b << 4 (shift 4 bits left)
	// x & (0011 0011)b
	// three results OR bitwise operate

	for( i = 0; i < size; ++i ){
		tmp[i] &= 0xff;
		tmp[i] = ( tmp[i] & 0x33 ) | ( (tmp[i] & 0xc0) >> 4 ) | ( (tmp[i] & 0x0c) << 4 ) ;
	}

	//step 3
	//xor 'a' with c0 and c3
	for( i = 0; i < size; i += 4 ){
		tmp[i] ^= 'a';
		tmp[i+3] ^= 'a';
	}


	//output the result
	printf("%s", tmp);

	//close file and free memory of char array pointer
	fclose(fp);
	free(tmp);

	return 0;
}